﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Bank_database_system
{
    public partial class 账号管理a : UserControl
    {
        public 账号管理a()
        {
            InitializeComponent();
            button1_Click(this, EventArgs.Empty);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            textBox5.Clear();
            comboBox1.Text = null;
            dataGridView1.DataSource = null;
            button1_Click(sender, e);
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        private void AddColumn(string columnName, string headerText, string dataPropertyName, bool isReadOnly = false)
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn
            {
                Name = columnName,
                HeaderText = headerText,
                DataPropertyName = dataPropertyName,
                ReadOnly = isReadOnly,
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Alignment = DataGridViewContentAlignment.MiddleCenter
                },
                HeaderCell = { Style = { Alignment = DataGridViewContentAlignment.MiddleCenter } }
            };
            dataGridView1.Columns.Add(column);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string staffIdPrefix = string.IsNullOrEmpty(textBox5.Text) ? null : textBox5.Text;
            string name = string.IsNullOrEmpty(textBox1.Text) ? null : textBox1.Text;
            string branchId = string.IsNullOrEmpty(textBox2.Text) ? null : textBox2.Text;
            string department = comboBox1.SelectedItem != null ? comboBox1.SelectedItem.ToString() : null;
            int pageNumber = Convert.ToInt32(label3.Text);
            int pageSize = 20;

            try
            {
                int maxPage = FunctionsforITDepartment.GetStaffTotalPageCount(staffIdPrefix, name, branchId, department, pageSize);
                label1.Text = Convert.ToString(maxPage > 1 ? maxPage : 1);

                DataTable staffData = FunctionsforITDepartment.GetStaff(staffIdPrefix, name, branchId, department, pageNumber, pageSize);

                // 过滤掉名称为“系统”的行
                var filteredRows = staffData.AsEnumerable()
                                            .Where(row => !row.Field<string>("name").Equals("系统", StringComparison.OrdinalIgnoreCase))
                                            .ToList();

                if (filteredRows.Any())
                {
                    staffData = filteredRows.CopyToDataTable();
                }
                else
                {
                    staffData = staffData.Clone(); // 或者创建一个空的 DataTable
                }

                dataGridView1.RowHeadersVisible = false;
                dataGridView1.AutoGenerateColumns = false; // 禁用自动生成列
                dataGridView1.AllowUserToAddRows = false; // 禁用添加空白行
                dataGridView1.Columns.Clear(); // 清除已有列
                dataGridView1.DoubleBuffered(true); // 双缓冲

                // 使用通用方法添加列
                AddColumn("StaffId", "工号", "staff_id");
                AddColumn("Name", "姓名", "name");
                AddColumn("BranchId", "支行", "branch_id");
                AddColumn("Department", "部门", "department");
                AddColumn("Password", "密码", "password", isReadOnly: true);

                // 添加重置密码按钮列
                DataGridViewButtonColumn resetPasswordColumn = new DataGridViewButtonColumn
                {
                    Name = "ResetPassword",
                    HeaderText = "重置密码",
                    Text = "重置",
                    UseColumnTextForButtonValue = true,
                    Width = 100,
                    HeaderCell = { Style = { Alignment = DataGridViewContentAlignment.MiddleCenter } }
                };
                dataGridView1.Columns.Add(resetPasswordColumn);

                dataGridView1.DataSource = staffData; // 绑定过滤后的数据

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 列宽自动调整模式

                // 订阅事件
                dataGridView1.CellFormatting -= DataGridView1_CellFormatting;
                dataGridView1.CellFormatting += DataGridView1_CellFormatting;
                dataGridView1.CellContentClick -= dataGridView1_CellContentClick;
                dataGridView1.CellContentClick += dataGridView1_CellContentClick;

            }
            catch (Exception ex)
            {
                // 错误处理
            }
        }


        private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 确保我们只格式化密码列
            if (dataGridView1.Columns[e.ColumnIndex].Name == "Password")
            {
                e.Value = "******"; // 用“******”替换实际密码
                e.FormattingApplied = true; // 标记格式化已应用
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是重置密码按钮列
            if (e.ColumnIndex == dataGridView1.Columns["ResetPassword"].Index && e.RowIndex >= 0)
            {
                // 获取当前行的 staffId 或其他标识符
                string staffId = dataGridView1.Rows[e.RowIndex].Cells["StaffId"].Value.ToString();
                try
                {
                    // 调用重置密码函数
                    FunctionsforITDepartment.ResetPassword(staffId);

                    MessageBox.Show("密码已重置为123456", "提示");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("重置密码失败: " + ex.Message, "错误");
                }
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            updateMaxPage();
            int page = Convert.ToInt32(label3.Text);
            int maxPage = Convert.ToInt32(label1.Text);
            page--;
            if (page < 1)
            {
                page = 1;
            }
            else if (page > maxPage)
            {
                page = maxPage;
            }
            label3.Text = Convert.ToString(page);
            button1_Click(this, EventArgs.Empty);

        }

        private void button13_Click(object sender, EventArgs e)
        {
            updateMaxPage();
            int page = Convert.ToInt32(label3.Text);
            int maxPage = Convert.ToInt32(label1.Text);
            page++;
            if (page < 1)
            {
                page = 1;
            }
            else if (page > maxPage)
            {
                page = maxPage;
            }
            label3.Text = Convert.ToString(page);
            button1_Click(this, EventArgs.Empty);
        }

        private void updateMaxPage()
        {
            string staffIdPrefix = string.IsNullOrEmpty(textBox5.Text) ? null : textBox5.Text;
            string name = string.IsNullOrEmpty(textBox1.Text) ? null : textBox1.Text;
            string branchId = string.IsNullOrEmpty(textBox2.Text) ? null : textBox2.Text;
            string department = comboBox1.SelectedItem != null ? comboBox1.SelectedItem.ToString() : null;
            int pageSize = 20;

            try
            {
                int maxPage = FunctionsforITDepartment.GetStaffTotalPageCount(staffIdPrefix, name, branchId, department, pageSize);
                label1.Text = Convert.ToString(maxPage > 1 ? maxPage : 1);
            }
            catch (Exception ex)
            {
                // 错误处理
            }
        }

    }
}
